/**
 * Copyright &copy; 2013-2016 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.cms.web;

import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.web.BaseController;
import cn.net.ecode.modules.cms.entity.Article;
import cn.net.ecode.modules.cms.entity.Category;
import cn.net.ecode.modules.cms.entity.Site;
import cn.net.ecode.modules.cms.service.CategoryService;
import cn.net.ecode.modules.cms.service.FileTplService;
import cn.net.ecode.modules.cms.utils.CmsUtils;
import cn.net.ecode.modules.sys.entity.Office;

/**
 * 栏目Controller
 * @author ThinkGem
 * @version 2014-9-16
 */
@Controller
@RequestMapping(value = "${adminPath}/cms/category")
public class CategoryController extends BaseController {

	@Autowired
	private CategoryService categoryService;
    @Autowired
   	private FileTplService fileTplService;
	
	@ModelAttribute
	public Category get(String categoryCode, boolean isNewRecord) {
		CmsUtils.getSite(Site.MAIN_SITE_CODE); // 用于初始化站点数据
		return categoryService.get(categoryCode, isNewRecord);
	}

//	@RequiresPermissions("cms:category:view")
	@RequestMapping(value = {"list", ""})
	public String list(Model model) {
		return "modules/cms/categoryList";
	}
	
//	@RequiresPermissions("cms:category:view")
	@ResponseBody
	@RequestMapping(value = "listData")
	public List<Category> listData(Category category, Model model) {
		if (StringUtils.isBlank(category.getParentCode())) {
			category.setParentCode(Office.ROOT_CODE);
		}
		category.setSite(new Site(Site.getCurrentSiteCode()));
		List<Category> list = null;
		if (StringUtils.isNotBlank(category.getCategoryCode())){
			list = Lists.newArrayList(get(category.getCategoryCode(), false));
		}else{
			list = categoryService.findList(category);
		}
		return list;
	}

//	@RequiresPermissions("cms:category:view")
	@RequestMapping(value = "form")
	public String form(Category category, Model model) {
		if (category.getParent()!=null && StringUtils.isNotBlank(category.getParent().getId())){
			category.setParent(categoryService.get(category.getParent().getCategoryCode()));
			// 获取排序号，最末节点排序号+30
			if (StringUtils.isBlank(category.getCategoryCode())){
				Category categoryChild = new Category();
				categoryChild.setParent(new Category(category.getParentCode()));
				List<Category> list = categoryService.findList(category); 
				if (list.size() > 0){
					category.setSorts(list.get(list.size()-1).getSorts());
					if (category.getSorts() != null){
						category.setSorts(category.getSorts() + 30);
					}
				}
			}
			if (category.getParent() != null){
				// 继承上级的模块类型
				if (StringUtils.isBlank(category.getModule())){
					category.setModule(category.getParent().getModule());
				}
				// 继承上级的视图配置参数
				if (StringUtils.isBlank(category.getViewConfig())){
					category.setViewConfig(category.getParent().getViewConfig());
				}
			}
		}
		if (category.getSorts() == null){
			category.setSorts(30);
		}
		if (category.getInMenu() == null){
			category.setInMenu(Global.HIDE);
		}
		if (category.getInList() == null){
			category.setInList(Global.SHOW);
		}
        model.addAttribute("listViewList", fileTplService.getTplContent(Category.DEFAULT_TEMPLATE));
        model.addAttribute("category_DEFAULT_TEMPLATE", Category.DEFAULT_TEMPLATE);
        model.addAttribute("contentViewList", fileTplService.getTplContent(Article.DEFAULT_TEMPLATE));
        model.addAttribute("article_DEFAULT_TEMPLATE", Article.DEFAULT_TEMPLATE);
		model.addAttribute("category", category);
		return "modules/cms/categoryForm";
	}
	
	@RequiresPermissions("cms:category:edit")
	@ResponseBody
	@RequestMapping(value = "save")
	public String save(Category category, Model model, RedirectAttributes redirectAttributes) {
		StringBuilder message = new StringBuilder();
		if (!beanValidator(message, category)){
			return renderResult(Global.FALSE, message);
		}
		if (Category.ROOT_CODE.equals(category.getPid())){
			category.setSite(new Site(Site.getCurrentSiteCode()));
		}else if (StringUtils.isNotBlank(category.getParent().getId())){
			category.setSite(categoryService.get(category.getParent()).getSite());
		}
		// 同步到ID
		if (category.getParent() != null){
			category.getParent().setId(category.getParent().getCategoryCode());
		}
		categoryService.save(category);
		return renderResult(Global.TRUE, "保存栏目'" + category.getCategoryName() + "'成功！");
	}
	
	@RequiresPermissions("cms:category:edit")
	@ResponseBody
	@RequestMapping(value = "delete")
	public String delete(Category category, RedirectAttributes redirectAttributes) {
		if (Category.ROOT_CODE.equals(category.getCategoryCode())){
			return renderResult(Global.FALSE, "删除栏目失败, 不允许删除顶级栏目或编号为空");
		}
		categoryService.delete(category);
		return renderResult(Global.TRUE, "删除栏目成功！");
	}
	
	/**
	 * 批量修改栏目排序
	 */
	@RequiresPermissions("cms:category:edit")
	@ResponseBody
	@RequestMapping(value = "updateSorts")
	public String updateSorts(String[] ids, Integer[] sorts, RedirectAttributes redirectAttributes) {
    	for (int i = 0; i < ids.length; i++) {
    		Category category = new Category(ids[i]);
    		category.setSorts(sorts[i]);
    		categoryService.updateSorts(category);
		}
		return renderResult(Global.TRUE, "保存栏目排序成功！");
	}
	
	
	/**
	 * 获取栏目树数据
	 * @param siteCode 指定站点
	 * @param module 指定模型
	 * @param extId 排除的编号ID
	 * @param canAdmin 是否仅获取可管理的栏目，指定 true 或 false
	 * @param isShowCode 是否显示编码（true or 1：显示在左侧；2：显示在右侧；false or null：不显示）
	 * @param response
	 * @return
	 */
//	@RequiresUser
	@RequiresPermissions("user")
	@ResponseBody
	@RequestMapping(value = "treeData")
	public List<Map<String, Object>> treeData(String extCode, String canAdmin, HttpServletResponse response) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		List<Category> list = categoryService.findAllList(new Category());
		for (int i=0; i<list.size(); i++){
			Category e = list.get(i);
			if ((StringUtils.isBlank(extCode) || (extCode!=null && !extCode.equals(e.getCategoryCode()) && e.getParentCodes().indexOf(","+extCode+",")==-1))
					&&(e.getStatus().equals("0"))){
				Map<String, Object> map = Maps.newHashMap();
				map.put("id", e.getCategoryCode());
				map.put("pId", e.getParentCode());
				map.put("pIds", e.getParentCodes());
				map.put("name", e.getCategoryName());
				// 是否仅获取可管理的栏目，指定 true 或 false
				if (StringUtils.toBoolean(canAdmin)){
					String adminUrl = e.getAdminUrl();
					if (!"none".equals(adminUrl)){
						map.put("adminUrl", "".equals(adminUrl) ? "none" : adminUrl);
						mapList.add(map);
					}
				}else{
					mapList.add(map);
				}
			}
		}
		return mapList;
	}
}
